from server.app.cloud_ide.schema.ide.request.ide_create_request import IdeCreateRequest
from server.app.cloud_ide.schema.ide.request.ide_update_request import IdeUpdateRequest
from server.app.cloud_ide.service.ide_environment_service import IdeEnvironmentService
from server.app.cloud_ide.service.ide_image_service import IdeImageService
from server.app.cloud_ide.service.ide_registry_service import IdeRegistryService
from behave import *

from server.app.cloud_ide.service.ide_service import IdeService
from server.framework.core.database import SessionLocal
from server.framework.core.logger import logger

ide_registry_service = IdeRegistryService()
ide_image_service = IdeImageService()
ide_environment_service = IdeEnvironmentService()
ide_service = IdeService()

db = SessionLocal()


@step('删除以下开发环境')
def 删除以下镜像(context):
    names = [x['name'] for x in context.table]
    for name in names:
        target = ide_service.find_ide_by_name(db=db, name=name)
        if target is not None:
            ide_service.delete_ide(db=db, ids=[str(target.id)])


@step('修改开发环境[{ide_name}],使用镜像源[{registry_name}]下的镜像[{image_name}]作为开发镜像,使用配额[{environment_name}],名字修改为[{new_name}]')
def 修改开发环境_使用镜像源_下的镜像_作为开发镜像_使用配额_名字修改为_(context, ide_name, registry_name, image_name, environment_name, new_name):
    registry = ide_registry_service.find_ide_registry_by_name(db=db, name=registry_name)
    image = ide_image_service.find_ide_image_by_name(db=db, registry_id=registry.id, name=image_name)
    environment = ide_environment_service.find_ide_environment_by_name(db=db, name=environment_name)
    ide = ide_service.find_ide_by_name(db=db, name=ide_name)
    ide_service.update_ide(db=db, data=IdeUpdateRequest(
        name=new_name,
        ide_image_id=str(image.id),
        ide_environment_id=str(environment.id),
        status=0,
        id=str(ide.id)
    ))


@step('使用镜像源[{registry_name}]下的镜像[{image_name}]作为开发镜像,使用配额[{environment_name}],创建如下开发环境')
def 新增开发环境_信息如下(context, registry_name, image_name, environment_name):
    registry = ide_registry_service.find_ide_registry_by_name(db=db, name=registry_name)
    image = ide_image_service.find_ide_image_by_name(db=db, registry_id=registry.id, name=image_name)
    environment = ide_environment_service.find_ide_environment_by_name(db=db, name=environment_name)
    for row in context.table:
        ide_service.create_ide(db=db, user_name='demo', user_id='demo', data=IdeCreateRequest(
            name=row['name'],
            ide_image_id=str(image.id),
            ide_environment_id=str(environment.id),
            status=0
        ))
